<template>
  <div class="add-goods-container">
    <div class="step">
      <el-steps :active="active" finish-status="success">
        <el-step title="填写商品信息"></el-step>
        <el-step title="确认提交"></el-step>
        <el-step title="添加成功"></el-step>
      </el-steps>
    </div>

    <!-- 商品信息表单 -->
    <div class="goods-info">
      <el-form ref="myForm" :model="form" label-width="100px" :rules="rules">
        <!-- 商品名称 -->
        <el-form-item label="商品名称" prop="name">
          <el-input v-model="form.name" clearable> </el-input>
        </el-form-item>
        <!-- 商品分类 -->
        <el-form-item label="商品分类">
          <el-cascader v-model="selectValue" :options="selectOptions" placeholder="请选择商品分类" @change="toggleSelectValue"></el-cascader>
        </el-form-item>

        <!-- 商品描述 -->
        <el-form-item label="商品描述" prop="desc">
          <el-input type="textarea" v-model="form.desc"></el-input>
        </el-form-item>

        <!-- 商品价格 -->
        <el-form-item label="商品价格">
          <el-input type="number" v-model="form.price"></el-input>
        </el-form-item>

        <!-- 商品数量 -->
        <el-form-item label="商品数量" prop="count">
          <el-input type="number" v-model="form.count"></el-input>
        </el-form-item>

        <!-- 商品规格 -->
        <el-form-item label="商品规格" prop="specs">
          <el-input v-model="form.specs"></el-input>
        </el-form-item>

        <!-- 商品货号 -->
        <el-form-item label="商品货号" prop="no">
          <el-input v-model="form.no"></el-input>
        </el-form-item>

        <!-- 商品封面图 -->
        <el-form-item label="商品图" prop="src">
          <div class="upload-img" :style="`background-image: url(${form.src});`">
            <input class="upload" type="file" ref="fileEdit" multiple accept="image/gif,image/jpeg,image/jpg,image/png" @change="editHead" />
            <el-icon v-if="form.src === ''"><Plus /></el-icon>
          </div>
        </el-form-item>

        <!-- 是否为店面推荐 -->
        <el-form-item label="是否店面推荐">
          <el-switch v-model="form.recommend"></el-switch>
        </el-form-item>

        <!-- 是否最新 -->
        <el-form-item label="是否最新">
          <el-switch v-model="form.new"></el-switch>
        </el-form-item>

        <!-- 是否轮播展示 -->
        <el-form-item label="是否轮播">
          <el-switch v-model="form.banner"></el-switch>
        </el-form-item>

        <el-form-item>
          <div style="text-align: center">
            <el-button type="primary" @click="onSubmit(myForm)" :loading="loading">{{ buttonText }}</el-button>
          </div>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { ElMessage } from 'element-plus'
import { reactive, ref } from 'vue'
import axios from '@/utils/request'
import { useRouter } from 'vue-router'
import { Plus } from '@element-plus/icons-vue'

let validatePass = (rule, value, callback) => {
  if (value <= 0) {
    callback(new Error('商品数量必须大于0'))
  }
}
const myForm = ref()
const router = useRouter()
let form = reactive({
  name: '',
  cate_id: '',
  desc: '',
  src: '',
  price: 0.0,
  count: 0,
  specs: '',
  no: '',
  recommend: false,
  new: true,
  img_type: '',
  banner: false
})
let active = ref(0)
let buttonText = ref('下一步，确认商品信息')
const selectValue = ref([]) // 选中的分类数据
const selectOptions = ref([]) // 筛选框中分类数据
let loading = ref(false)
let rules = reactive({
  name: [
    { required: true, message: '请输入商品名称', trigger: 'blur' },
    { min: 1, max: 255, message: '长度在 1 到 255 个字符', trigger: 'blur' }
  ],
  desc: [{ min: 0, max: 500, message: '长度在500以内', trigger: 'blur' }],
  src: [{ required: true, message: '请上传商品图片', trigger: 'blur' }],
  no: [{ required: true, message: '请输入商品货号', trigger: 'blur' }],
  specs: [{ required: true, message: '请输入商品规格', trigger: 'blur' }],
  count: [{ validator: validatePass, trigger: 'blur' }]
})

//#region
// 获取一级分类
const getCateList = async () => {
  try {
    const data = await axios.get('/bus/category/list')
    if (data.code === 0) {
      // 获取一级分类成功
      data.data.forEach((item) => {
        // 遍历一级分类发起请求获取二级分类
        getSonCateList(item)
      })
    } else if (data.msg === '身份认证失败' || data.code === 403) {
      ElMessage({
        type: 'error',
        message: data.msg
      })
      localStorage.removeItem('bus_token')
      router.replace('/login')
    } else {
      ElMessage({
        type: 'error',
        message: data.msg
      })
    }
  } catch {
    ElMessage.error('请求失败！')
  }
}
//     // 获取二级分类
const getSonCateList = async (item) => {
  const cate = {
    value: item.id,
    label: item.name,
    children: ref([])
  }
  try {
    const data = await axios.get('/bus/category/list/' + item.id)
    if (data.code === 0) {
      // 获取成功
      if (data.data.length > 0) {
        data.data.forEach((cateItem) => {
          cate.children.value.push({
            value: cateItem.id,
            label: cateItem.name
          })
        })
      }
      selectOptions.value.push(cate)
    } else if (data.msg === '身份认证失败' || data.code === 403) {
      ElMessage({
        type: 'error',
        message: data.msg
      })
      localStorage.removeItem('bus_token')
      router.replace('/login')
    } else {
      ElMessage({
        type: 'error',
        message: data.msg
      })
    }
  } catch (err) {
    ElMessage.error('请求失败！')
  }
}
// 切换当前选中的值
const toggleSelectValue = (val) => {
  form.cate_id = val[1] ? val[1] : val[0]
}
// 上传图片后将图片路径转换为base64
const editHead = (e) => {
  let fileData = e.target.files[0]
  const type = fileData.type.split('/')[1]
  form.img_type = type
  const reader = new FileReader()
  reader.readAsDataURL(fileData)
  reader.onload = (e) => {
    form.src = e.target.result
  }
}
//#endregion

// 表单验证
const formValidator = () => {
  // 商品名称不为空
  if (form.name == '') {
    return ElMessage({
      type: 'error',
      message: '请输入商品名称！'
    })
  }
  // 必须选择分类
  if (form.cate_id === '') {
    return ElMessage({
      type: 'error',
      message: '请选择分类！'
    })
  }
  // 商品描述长度不能超过500
  if (form.desc.length > 500) {
    return ElMessage({
      type: 'error',
      message: '商品描述长度不能超过500!'
    })
  }

  // 商品价格必须大于等于0
  if (form.price < 0) {
    return ElMessage({
      type: 'error',
      message: '商品价格必须大于等于0！'
    })
  }

  // 商品数量必须大于0
  if (form.count <= 0) {
    return ElMessage({
      type: 'error',
      message: '商品数量必须大于0！'
    })
  }

  // 商品规格不为空
  if (form.specs === '') {
    return ElMessage({
      type: 'error',
      message: '请输入商品规格！'
    })
  }

  // 商品货号不为空
  if (form.no === '') {
    return ElMessage({
      type: 'error',
      message: '请输入商品货号！'
    })
  }

  // 商品货号为数字字母组合
  if (!/^[A-Za-z]{1,}\d+$/.test(form.no)) {
    return ElMessage({
      type: 'error',
      message: '商品货号为数字字母组合，且字母在前，数字在后！'
    })
  }

  // 商品图片不为空
  if (form.src === '') {
    return ElMessage({
      type: 'error',
      message: '请上传商品图片！'
    })
  }
  // 只能是以下四种格式
  if (['png', 'jpg', 'jpeg', 'gif'].indexOf(form.img_type) === -1) {
    return ElMessage({
      type: 'error',
      message: '商品图片格式错误！'
    })
  }
  return true
}
// 提交添加的商品
const onSubmit = async (formEl) => {
  const validatorRes = formValidator()
  if (validatorRes === true) {
    switch (active.value) {
      case 0:
        // 验证表单数据
        active.value++
        buttonText.value = '提交'
        break
      case 1:
        active.value++
        loading.value = true
        // 发起请求添加商品
        try {
          const data = await axios.post('/bus/add/goods', form)
          if (data.code === 0) {
            // 上传成功
            active.value++
            buttonText.value = '重置'
          } else if (data.msg === '身份验证失败！') {
            // 删除本地token
            localStorage.removeItem('bus_token')
            router.replace('/login')
          } else {
            active.value--
            ElMessage({
              type: 'error',
              message: data.msg
            })
          }
        } catch {
          ElMessage.error('请求失败！')
        } finally {
          loading.value = false
        }
        break
      default:
        active.value = 0
        buttonText.value = '下一步，确认商品信息'
        formEl.resetFields()
        selectValue.value = []
        // 清空表单数据
        form.name = ''
        form.cate_id = ''
        form.desc = ''
        form.src = ''
        form.price = 0.0
        form.count = 0
        form.specs = ''
        form.no = ''
        form.recommend = false
        form.new = true
        form.img_type = ''
        form.banner = false
    }
  } else {
    return
  }
}

getCateList()
</script>

<style lang="scss" scoped>
.add-goods-container {
  margin: 50px auto;
  border: 1px solid #e1e1e1;
  width: 860px;
  padding: 50px 100px 0;
  box-sizing: border-box;

  .step {
    width: 90%;
    margin: 0 auto;
  }

  .goods-info {
    margin-top: 20px;

    .upload-img {
      border: 1px dashed #e1e1e1;
      height: 80px;
      width: 80px;
      background-repeat: no-repeat;
      background-size: 100% 100%;
      display: flex;
      align-items: center;
      justify-content: center;
      position: relative;

      .upload {
        position: absolute;
        height: 100%;
        width: 100%;
        z-index: 999;
        opacity: 0;
      }

      .el-icon {
        font-size: 24px;
        color: #e1e1e1;
      }
    }
  }
}
</style>
